import { Message } from 'element-ui'

class NotificationManager {
  constructor() {
    this.messageQueue = []
    this.isProcessing = false
    this.lastMessageTime = 0
    this.minInterval = 300 // Minimum interval between messages in ms
    this.currentMessage = null
  }

  showMessage(options) {
    // If same message as last one, skip it
    if (this.lastMessage && this.lastMessage.message === options.message) {
      return
    }

    this.messageQueue.push(options)
    this.processQueue()
  }

  processQueue() {
    if (this.isProcessing || this.messageQueue.length === 0) {
      return
    }

    this.isProcessing = true
    const now = Date.now()
    const timeSinceLastMessage = now - this.lastMessageTime

    if (timeSinceLastMessage < this.minInterval) {
      // Wait before showing next message
      setTimeout(() => {
        this.isProcessing = false
        this.processQueue()
      }, this.minInterval - timeSinceLastMessage)
      return
    }

    const options = this.messageQueue.shift()
    this.lastMessage = options
    this.lastMessageTime = now

    // Close previous message if it exists
    if (this.currentMessage) {
      this.currentMessage.close()
    }

    // Show the message
    this.currentMessage = Message({
      ...options,
      duration: options.duration || 3000,
      onClose: () => {
        this.currentMessage = null
      }
    })

    this.isProcessing = false

    // Process next message if exists
    if (this.messageQueue.length > 0) {
      setTimeout(() => {
        this.processQueue()
      }, this.minInterval)
    }
  }

  success(message, options = {}) {
    this.showMessage({
      type: 'success',
      message,
      ...options
    })
  }

  error(message, options = {}) {
    this.showMessage({
      type: 'error',
      message,
      duration: 5000, // Errors stay longer
      ...options
    })
  }

  warning(message, options = {}) {
    this.showMessage({
      type: 'warning',
      message,
      ...options
    })
  }

  info(message, options = {}) {
    this.showMessage({
      type: 'info',
      message,
      ...options
    })
  }

  clear() {
    this.messageQueue = []
    if (this.currentMessage) {
      this.currentMessage.close()
      this.currentMessage = null
    }
  }
}

// Create singleton instance
const notificationManager = new NotificationManager()

// Vue plugin
export default {
  install(Vue) {
    Vue.prototype.$notify = notificationManager
  }
}

export { notificationManager }